package the.guanzhong.express.interfaces.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.wisteria.framework.web.APIResult;
import org.wisteria.framework.web.BusinessException;
import org.wisteria.framework.web.QueryResult;
import the.guanzhong.express.interfaces.controller.req.RefundAuditReq;
import the.guanzhong.express.interfaces.controller.req.RefundPageReq;
import the.guanzhong.express.interfaces.controller.req.RefundQueryReq;
import the.guanzhong.express.interfaces.controller.resp.RefundItemResp;
import the.guanzhong.express.service.ExpressRefundService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@Api(tags = "Express")
@Slf4j
@RestController
@RequestMapping("/express/refund")
public class ExpressRefundController {

    @Resource
    private ExpressRefundService expressRefundService;

    @PostMapping("/query")
    public APIResult<List<RefundItemResp>> query(@RequestBody @Valid RefundQueryReq req) {
        return APIResult.success(expressRefundService.query(req));
    }

    @GetMapping("/page")
    public APIResult<QueryResult<RefundItemResp>> page(RefundPageReq req) {
        return APIResult.success(expressRefundService.page(req));
    }

    @PostMapping("/audit")
    public APIResult<Boolean> audit(@RequestBody @Valid RefundAuditReq req) {
        return APIResult.success(expressRefundService.audit(req));
    }

    @PostMapping("/notify")
    public APIResult<Boolean> notify(HttpServletRequest request) {
        BufferedReader br;
        StringBuilder wholeParams = new StringBuilder();
        try {
            br = request.getReader();
            String str;
            while((str = br.readLine()) != null){
                wholeParams.append(str);
            }
        } catch (IOException e) {
            log.error("接收退款回调请求异常", e);
            throw new BusinessException("接收退款回调请求异常");
        }

        log.info("接收退款回调请求:" + wholeParams);
        WxPayRefundNotifyResult result = BaseWxPayResult.fromXML(wholeParams.toString(), WxPayRefundNotifyResult.class);
        if (WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())
                && WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())) {
            expressRefundService.completeRefund(result);
        }
        return APIResult.success(true);
    }
}
